// 线程安全队列
#include <queue>
#include <mutex>
#include <condition_variable>

class data_chunk { };

template<typename T>
class ThreadSafe_queue {
private:
    // 其他线程可能有类型的非const引用对象，并调用变种成员函数，有必要为互斥量上锁
    mutable std::mutex mtx; 
    std::queue<T> data_queue;
    std::condition_variable data_cond;
public:
    void push(T new_val) {
        std::lock_guard<std::mutex> lk(mtx);
        data_queue.push(new_val);
        data_cond.notify_one(); // notify data add.
    }

    void wait_and_pop(T& value) {
        std::unique_lock<std::mutex> lk(mtx);
        data_cond.wait(lk, [this] {
            return !data_queue.empty(); // wait until has data
        });
        value = data_queue.front();
        data_queue.pop();
    }

    std::shared_ptr<T> wait_and_pop() {
        std::unique_lock<std::mutex> lk(mtx);
        data_cond.wait(lk, [this] {
            return !data_queue.empty();
        });
        std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
        data_queue.pop();
        return res;
    }

    bool try_pop(T& val) {
        std::lock_guard<std::mutex> lk(mtx);
        if (data_queue.empty()) {
            return false;
        }
        val = data_queue.front();
        data_queue.pop();
        return true;
    }

    std::shared_ptr<T> try_pop() {
        std::lock_guard<std::mutex> lk(mtx);
        if (data_queue.empty()) {
            return std::shared_ptr<T>();
        }
        std::shared_ptr<T> res(std::make_shared<T>(data_queue.front()));
        data_queue.pop();
        return res;
    }

    bool empty() const {
        std::lock_guard<std::mutex> lk(mtx);
        return data_queue.empty();
    }
};
